//
//  ConnectModel.m
//  网络封装
//
//  Created by 杨利佳 on 15/5/7.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "ConnectModel.h"

@implementation ConnectModel

- (void)dealloc
{
    [_receiveData release];
    [super dealloc];
}

+ (void)connectWithUrl:(NSString *)url block:(void (^)(NSData *data))block
{
    ConnectModel *model = [[ConnectModel alloc] init];
    model.finishedBlock = block;
    [model startConnection:url];
    [model release];

}

- (void)startConnection:(NSString *)str
{
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    
    // 异步网络连接
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.receiveData = [NSMutableData data];
}

// 接收服务器返回的数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_receiveData appendData:data];
}

// 数据接收完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishedBlock(_receiveData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error = %@", error);
}

@end
